<?php

class Packing_list_packagesController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to 'column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='column2';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array(),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','viewpackages','delete','gridcargo','view'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	/**
	 * Displays a particular model.
	 */
	public function actionView(){
		$dataProvider=new CActiveDataProvider('packing_list_packages_cargo',array(
			'criteria'=>array(
				'condition'=>'package_id='.$_GET['id'],
			),
		));
		$this->render('view',array(
			'model'=>$this->loadModel(),
			'cargos'=>$dataProvider,
		));
	}
	public function actionGetCargo(){
		$model = new cargo;
		$model->searchText = $_GET['term'];
		$datas = $model->in_warehouse()->getData();
		$_data = array();
		foreach($datas as $data) {
			$_data[] = array('id'=>$data->id,'value'=>$data->do_ref->ref_no);
		}
		echo CJavaScript::jsonEncode($_data);
	}
	public function actionViewPackages(){
		$model = $this->loadModel();
		echo $this->renderPartial('_view',array('data'=>$model),true,true);
	}
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$models['package'][0] =new packing_list_packages;
		$models['detail'][0] = new packing_list_packages_dimension;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['packing_list_packages'])) {
			$this->AssignData($models['detail'],'packing_list_packages_dimension');
			$this->AssignData($models['package'],'packing_list_packages');
			foreach($models['package'] as $model) {
				$model->packing_list_id = $_GET['pid'];
			}
			$this->validateModels($models);
			$ajax = (isset($_POST['ajax']) && $_POST['ajax']==='packing-list-packages-form' && Yii::app()->request->isAjaxRequest)?true:false;
			$transaction = Yii::app()->db->beginTransaction();
			try{
				foreach($models['package'] as $i=>$model) {
					if(!$model->save())
						throw new Exception("Saving error.");
					if(!$model->Add($models['detail'][$i],'foreign_key'))
						throw new Exception("Relation save error.");
				}
				$transaction->commit();
				if($ajax){
					echo CJavaScript::jsonEncode(array('id'=>$models['package'][0]->packing_list_id));
					Yii::app()->end();
				}
				else
					$this->redirect(array('view','id'=>$model['package']->id));
            }
            catch(Exception $e) {
            	$transaction->rollback();
            	if($ajax){
            		echo CJavaScript::jsonEncode(array('formerror'=>$e->getMessage()));
            		Yii::app()->end();
            	}
            }
		}
		if(Yii::app()->request->isAjaxRequest){
			echo $this->renderPartial('create',array('models'=>$models),true,true);
			Yii::app()->end();	
		}			
		$this->render('create',array(
			'models'=>$models,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate()
	{
		$model['package']=$this->loadModel();
		$model['detail'] = $model['package']->detail;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['packing_list_packages']))
		{
			$model['detail']->attributes = $_POST['packing_list_packages_dimension'];
			$model['package']->attributes=$_POST['packing_list_packages'];
			$this->validateModels($model);
			$ajax = (isset($_POST['ajax']) && $_POST['ajax']==='packing-list-packages-update-form' && Yii::app()->request->isAjaxRequest)?true:false;
			$transaction = Yii::app()->db->beginTransaction();
			try{
				if($model['package']->save()){
					
					if(
						!$model['package']->Add($model['detail'],'foreign_key')
					)
						throw new Exception('Relation add error');					
					$transaction->commit();
				}
            }
            catch(Exception $e) {
            	$transaction->rollback();
            	if($ajax){
            		echo CJavaScript::jsonEncode(array('formerror'=>$e->getMessage()));
            		Yii::app()->end();
            	}
            }
			if($ajax){
				echo CJavaScript::jsonEncode(array('id'=>$model['package']->id));
				Yii::app()->end();
			}
			else
				$this->redirect(array('view','id'=>$model['package']->id));
		}
		if(Yii::app()->request->isAjaxRequest) {
			echo $this->renderPartial('update',array('model'=>$model),true,true);
			Yii::app()->end();
		}
		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel()->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!Yii::app()->request->isAjaxRequest)
				$this->redirect(array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('packing_list_packages');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new packing_list_packages('search');
		if(isset($_GET['packing_list_packages']))
			$model->attributes=$_GET['packing_list_packages'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=packing_list_packages::model()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='packing-list-packages-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
